#include "order_handler_impl.h"
#include "spdlog/spdlog.h"

OrderHandlerImpl::OrderHandlerImpl(
    std::shared_ptr<hft::OrderManager> manager,
    std::unique_ptr<MarketDataValidator> validator,
    std::unique_ptr<RateLimiter> limiter)
    : manager_(std::move(manager)),
      validator_(std::move(validator)),
      limiter_(std::move(limiter)),
      batchSize_(10),
      lastBatchTime_(std::chrono::steady_clock::now()) {}

void OrderHandlerImpl::processBatch(const std::vector<Order>& orders) {
    if (orders.empty()) return;

    // 限流检查
    if (!limiter_->tryAcquire(orders.size())) {
        SPDLOG_WARN("Rate limit exceeded, batch size: {}", orders.size());
        return;
    }

    // 验证市场数据
    for (const auto& order : orders) {
        if (!validator_->validate(order)) {
            SPDLOG_ERROR("Invalid market data for order {}", order.id());
            continue;
        }
        
        try {
            manager_->processOrder(order);
        } catch (const std::exception& e) {
            SPDLOG_ERROR("Order processing failed: {}", e.what());
        }
    }

    // 调整批次大小
    adjustBatchSize();
    lastBatchTime_ = std::chrono::steady_clock::now();
}

void OrderHandlerImpl::adjustBatchSize() {
    // 基于处理时间的自适应算法
    auto elapsed = std::chrono::steady_clock::now() - lastBatchTime_;
    auto elapsedMs = std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();

    if (elapsedMs < 50) {
        batchSize_ = std::min(batchSize_ + 2, 100);
    } else if (elapsedMs > 100) {
        batchSize_ = std::max(batchSize_ - 1, 1);
    }
}